import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { CreateCategoryDto } from './dto/create-category.dto'
import { UpdateCategoryDto } from './dto/update-category.dto'
import { CategoryEntity } from './entities/category.entity'
import { IParamsResult } from '@/shared/core/decorator/ListParams.decorator'

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(CategoryEntity)
    private readonly categoryRepository: Repository<CategoryEntity>,
  ) {}

  // 新增
  async create(dto: CreateCategoryDto) {
    const result = await this.categoryRepository.create(dto)
    await this.categoryRepository.save(result)

    return result
  }

  // 列表
  findAll({ where, order }: IParamsResult) {
    return this.categoryRepository.find({ order, where })
  }

  // 详情
  findOne(id) {
    return this.categoryRepository.findOne({ where: { id } })
  }

  // 修改
  async update(id, dto: UpdateCategoryDto) {
    const old = await this.findOne(id)
    const vo = await this.categoryRepository.merge(old, dto)

    return this.categoryRepository.save(vo)
  }

  // 删除
  async remove(id) {
    const result = await this.categoryRepository.delete(id)
    Logger.log(`删除返回数据：${JSON.stringify(result)}`)

    return result.affected || new HttpException('无法删除，请稍候在试', HttpStatus.BAD_REQUEST)
  }
}
